package com.ljn.springboot.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljn.springboot.entity.User;
import com.ljn.springboot.exception.ServiceException;
import com.ljn.springboot.mapper.UserMapper;
import com.ljn.springboot.service.UserService;
import com.ljn.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User login(User user) throws ServiceException {
        User dbUser = selectByUserName(user.getUsername());
        if (dbUser == null) {
            throw new ServiceException("用户名或密码错误");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {

            throw new ServiceException("用户名或密码错误");

        }
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }



    public User selectByUserName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        return getOne(queryWrapper);
    }
}